package com.springactiviti.activiti.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Controller
public class activitiController {

    //工作流引擎服务
    @Autowired
    private ProcessEngine processEngine;

    @Autowired
    private ObjectMapper objectMapper;

    @RequestMapping("/init")
    public String initModel() throws UnsupportedEncodingException {
        //管理仓库服务
        RepositoryService repositoryService=processEngine.getRepositoryService();
        //初始化一个空模型
        Model model=repositoryService.newModel();

        //基本信息
        //工作流名称
        String activityName="test";
        //说明
        String description="";
        //版本
        int version=1;
        //工作流唯一标识
        String activityKey="test";
        //创建一个json节点
        ObjectNode node=objectMapper.createObjectNode();
        node.put(ModelDataJsonConstants.MODEL_NAME,activityName);
        node.put(ModelDataJsonConstants.MODEL_DESCRIPTION,description);
        node.put(ModelDataJsonConstants.MODEL_REVISION,version);
        model.setKey(activityKey);
        model.setName(activityName);
        model.setMetaInfo(node.toString());
        //添加模型
        repositoryService.saveModel(model);
        String id=model.getId();

        //完善ModelEditorSource
        ObjectNode editNode=objectMapper.createObjectNode();
        editNode.put("id","canvas");
        editNode.put("resourceId","canvas");
        ObjectNode stencilSetNode = objectMapper.createObjectNode();
        stencilSetNode.put("namespace",
                "http://b3mn.org/stencilset/bpmn2.0#");
        editNode.put("stencilset", stencilSetNode);
        repositoryService.addModelEditorSource(id,editNode.toString().getBytes("utf-8"));
         /*ToWeb.buildResult().redirectUrl("/modeler.html?modelId="+id);*/
        return "redirect:/modeler.html?modelId="+id;
    }


   /* @GetMapping
    public List<Model> getListModel(){
        RepositoryService repositoryService=processEngine.getRepositoryService();
        List<Model> modes=repositoryService.createModelQuery().list();
        return modes;
    }*/
}
